/**
 * 极光短信的工具类
 */
//模拟发送http请求
let request = require("request");
let appKey = "373e8291110efd3cda16ddec";
let masterSecret = "0adf4b2c02ee02c3d8142e51";
//调用极光短信的url
let jiGuangSmsUrl = "https://api.sms.jpush.cn/v1/messages";
let sign_id = 10643;
let phone_code_temp_id = 169776;
const {BusiError, SysError} = require('../exception/exception');

class JiGuangSmsUtil{
    constructor(){
    }

    async sendMessage(mobile, temp_id, temp_para){
        let auth_sting = appKey + ":" + masterSecret;
        let base64_auth_string = new Buffer.from(auth_sting).toString("base64");
        //let base64_appKey = new Buffer.from(appKey).toString("base64");
        //let base64_masterSecret = new Buffer.from(masterSecret).toString("base64");
        let postHeaders = {};
        postHeaders["content-type"] = "application/json";
        postHeaders["Authorization"] = "Basic " + base64_auth_string;
        //postHeaders[base64_appKey] = base64_masterSecret;
        //post请求
        request({
            url: jiGuangSmsUrl,
            method: "post",//如果是post就涉及到跨域的问题了
            json: true,
            headers: postHeaders,
            body: {
                mobile: mobile,
                sign_id: sign_id,
                temp_id: temp_id,
                temp_para: temp_para
            }
        }, function (error, response, body) {
            console.log(body);
            if (!error && response.statusCode === 200) {
                return;
            }
            throw new BusiError(500, "短信发送失败");
        });
    }

    async sendPhoneCode(mobile, code){
        let temp_para = {code: code};
        await this.sendMessage(mobile, phone_code_temp_id,  temp_para);
    }

}

let jiGuangSmsUtil = new JiGuangSmsUtil();

module.exports = jiGuangSmsUtil;


